package com.zz.inventory.service.impl;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.zz.inventory.domain.Classes;
import com.zz.inventory.feign.TeacherExamFeignClient;
import com.zz.inventory.mapper.ClassesMapper;
import org.example.dto.StudentExamRecordDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zz.inventory.mapper.StudentsMapper;
import com.zz.inventory.domain.Students;
import com.zz.inventory.service.IStudentsService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 学生信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-03
 */
@Service
public class StudentsServiceImpl implements IStudentsService 
{
    @Autowired
    private TeacherExamFeignClient teacherFeignClient;
    @Autowired
    private StudentsMapper studentsMapper;
    @Autowired
    private ClassesMapper classesMapper;

    /*@Autowired
    private StudentExamRecordsMapper examRecordsMapper; // 操作student_exam_records表*/

    public StudentsServiceImpl(TeacherExamFeignClient teacherFeignClient, StudentsMapper studentsMapper) {
        this.teacherFeignClient = teacherFeignClient;
        this.studentsMapper = studentsMapper;
    }

    /**
     * 查询学生信息
     * 
     * @param studentId 学生信息主键
     * @return 学生信息
     */
    @Override
    public Students selectStudentsByStudentId(Long studentId)
    {
        return studentsMapper.selectStudentsByStudentId(studentId);
    }

    /**
     * 查询学生信息列表
     * 
     * @param students 学生信息
     * @return 学生信息
     */
    @Override
    public List<Students> selectStudentsList(Students students)
    {
        return studentsMapper.selectStudentsList(students);
    }

    /**
     * 新增学生信息
     * 
     * @param students 学生信息
     * @return 结果
     */
    @Override
    public int insertStudents(Students students)
    {
//        students.setStudentId(students.getStudentId());
        students.setCreateTime(DateUtils.getNowDate());
        return studentsMapper.insertStudents(students);
    }

    /**
     * 修改学生信息
     * 
     * @param students 学生信息
     * @return 结果
     */
    @Override
    public int updateStudents(Students students)
    {
        return studentsMapper.updateStudents(students);
    }

    /**
     * 批量删除学生信息
     * 
     * @param studentIds 需要删除的学生信息主键
     * @return 结果
     */
    @Override
    public int deleteStudentsByStudentIds(Long[] studentIds)
    {
        return studentsMapper.deleteStudentsByStudentIds(studentIds);
    }

    /**
     * 删除学生信息信息
     * 
     * @param studentId 学生信息主键
     * @return 结果
     */
    @Override
    public int deleteStudentsByStudentId(Long studentId)
    {
        return studentsMapper.deleteStudentsByStudentId(studentId);
    }

    /**
     * 导入学生信息
     *
     * @param studentsList 学生信息列表
     * @return 导入结果信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importStudents(List<Students> studentsList) {
        // 1. 数据校验
        if (CollectionUtils.isEmpty(studentsList)) {
            return "导入数据为空";
        }

        // 2. 验证班级是否存在（使用原有方法）
        Set<Long> notExistClassIds = new HashSet<>();
        for (Students student : studentsList) {
            if (student.getClassId() != null) {
                Classes classes = classesMapper.selectClassesByClassId(student.getClassId());
                if (classes == null) {
                    notExistClassIds.add(student.getClassId());
                } else {
                    // 可选：设置关联对象
                    student.setClasses(classes);
                }
            }
        }

        if (!notExistClassIds.isEmpty()) {
            throw new ServiceException("以下班级ID不存在: " + notExistClassIds);
        }

        // 3. 数据预处理
        studentsList.forEach(student -> {
            if (student.getClassId() != null) {
                Classes classes = classesMapper.selectClassesByClassId(student.getClassId());
                if (classes != null) {
                    // 从班级取 school_id 赋值
                    student.setSchoolId(classes.getSchoolId());
                }
            }
            if (student.getCreateTime() == null) student.setCreateTime(new Date());
            if (StringUtils.isNotBlank(student.getEnrollmentDateRaw())) {
                student.setEnrollmentDate(parseDate(student.getEnrollmentDateRaw()));
            }
        });

        // 4. 批量插入
        try {
            int affected = studentsMapper.batchInsertStudents(studentsList);
            return "成功导入" + affected + "条数据";
        } catch (Exception e) {
            throw new ServiceException("数据库操作失败: " + e.getMessage());
        }
    }

    @Override
    public boolean existsById(Long studentId) {
        return studentsMapper.selectStudentsByStudentId(studentId) != null;
    }


    @Override
    public int deleteStudentById(Long studentId) {
        return studentsMapper.deleteStudentsByStudentId(studentId);
    }


    /**
     * 多格式日期解析工具
     * @param rawDate 原始日期字符串（支持 dd/MM/yyyy, MM/dd/yyyy, yyyy-MM-dd 等格式）
     * @return 标准格式日期字符串（yyyy-MM-dd）
     * @throws IllegalArgumentException 当日期格式无法识别时抛出
     */
    private String parseDate(String rawDate) {
        if (StringUtils.isBlank(rawDate)) {
            return null;
        }

        // 支持的日期格式列表（按优先级排序）
        String[] patterns = {
                "dd/MM/yyyy", "d/M/yyyy",   // 欧洲/中国格式 如: 01/09/2024 或 1/9/2024
                "MM/dd/yyyy", "M/d/yyyy",   // 美国格式 如: 09/01/2024 或 9/1/2024
                "yyyy-MM-dd",                // ISO格式 如: 2024-09-01
                "yyyy/MM/dd", "yyyy/M/d",    // 其他常见格式
                "yyyy年MM月dd日"             // 中文格式
        };

        // 尝试按多种格式解析
        for (String pattern : patterns) {
            try {
                // 去除日期字符串中的中文符号和空格
                String cleanedDate = rawDate.replaceAll("[年月日\\s]", "");
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
                LocalDate date = LocalDate.parse(cleanedDate, formatter);
                return date.format(DateTimeFormatter.ISO_LOCAL_DATE); // yyyy-MM-dd
            } catch (DateTimeParseException ignored) {
                // 尝试下一种格式
            }
        }

        throw new IllegalArgumentException("无法识别的日期格式: " + rawDate +
                "。支持的格式示例: 01/09/2024, 9/1/2024, 2024-09-01");
    }
    // 新增带检查的删除方法


}
